import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yt_devops/components/brn/brn_delete_tag.dart';
import 'package:yt_devops/components/paging/model/paging_params.dart';
import 'package:yt_devops/pages/common/select_page/select_page_binding.dart';
import 'package:yt_devops/pages/common/select_page/select_page_model.dart';
import 'package:yt_devops/pages/common/select_page/select_page_view.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/utils/extensions.dart';

import 'filter_dialog.dart';

class FilterSiteTags extends StatefulWidget {
  //已选中的站点列表
  List<SiteTagModel> selectedSites;

  final double? tagWidth;

  void Function(List<SiteTagModel> sites)? onChange;
  FilterSiteTags(
      {super.key, this.tagWidth, this.selectedSites = const [], this.onChange});

  @override
  State<FilterSiteTags> createState() => _FilterSiteTagsState();
}

class _FilterSiteTagsState extends State<FilterSiteTags> {
  late YtBrnDeleteTagController controller;

  List<String> get siteNames =>
      widget.selectedSites.mapIndexed((e, idx) => e.name.toString()).toList();

  @override
  void initState() {
    controller = YtBrnDeleteTagController(initTags: siteNames);
    super.initState();
  }

  @override
  void didUpdateWidget(covariant FilterSiteTags oldWidget) {
    if (widget.selectedSites.isEmpty) {
      controller.clear();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        FilterDialogWidget.pickTitle(
          ResKey.site.tr,
        ),
        SizedBox(
          height: 3.h,
        ),
        YtBrnDeleteTag(
            key: UniqueKey(),
            firstBuilder: FilterDialogWidget.addTag(() => toSite()),
            padding: const EdgeInsets.only(left: 0),
            horizontalSpacing: 2.w,
            verticalSpacing: 10.h,
            themeData: BrnTagConfig(
                tagHeight: 34.h,
                tagWidth: widget.tagWidth ?? 104.w,
                tagMinWidth: widget.tagWidth ?? 104.w),
            onTagDelete: (p0, p1, index) {
              deleteSiteTag(index);
            },
            controller: controller),
      ],
    );
  }

  //删除掉已选的站点
  deleteSiteTag(
    int index,
  ) {
    widget.selectedSites.removeAt(index);
    if (widget.onChange != null) {
      widget.onChange!(widget.selectedSites);
    }
  }

  toSite() {
    Get.to(
      () => SelectPagePage<Map>(),
      routeName: RouterPath.selectPage,
      binding: SelectPageBinding<Map>(),
      arguments: SelectPageProp<Map>(
        ResKey.site.tr,
        getIdByKey: (data) => data['siteId'],
        getNameKey: (data) => data['name'],
        isSearch: true,
        isSingle: true,
        searchKey: 'name',
        initSelectValues: widget.selectedSites.isEmpty
            ? []
            : widget.selectedSites.map((e) => e.toJson()).toList(),
        service: (PagingParams pagingParams) => SiteServices().getSitesList({
          'current': pagingParams.pageNum,
          'pageSize': pagingParams.pageSize,
          "siteName": pagingParams.extra?['name'],
          "status": 2
        }),
      ),
    )?.then((value) {
      if (value is Map) {
        widget.selectedSites = [SiteTagModel.fromJson(value)];
        controller
          ..clear()
          ..addTags(siteNames);

        if (widget.onChange != null) {
          widget.onChange!(widget.selectedSites);
        }
      }
    });
  }
}

class SiteTagModel {
  int? siteId;
  String? name;
  bool isSelect = false;

  SiteTagModel({this.siteId, this.name});

  factory SiteTagModel.fromJson(Map jsons) =>
      SiteTagModel(siteId: jsons['siteId'], name: jsons['name']);

  Map<String, dynamic> toJson() => {
        'siteId': siteId,
        'name': name,
      };
}
